/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:11:20
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-07-28 18:00:40
 */
import { observable, action, computed, toJS, runInAction } from 'mobx';
import { message } from 'antd';
import { WeaTools, WeaLocaleProvider } from 'ecCom';

import Api from '../apis/new';
import { isSelectedAll } from '../util/index';

const getLabel = WeaLocaleProvider.getLabel;
const { Base64 } = WeaTools;
const noop = () => {};

const initState = {
  loading: false,
  sendingStatus: '',
  editing: false,
  initDatas: {},
  hideRight: { 0: false, 1: false },
  // initDatas mirror
  mailAccountId: '',
  hrmAccountid: '',
  isSendApart: 0,
  op_showInnerAndOuter: 0,
  innerMail: 1,
  outerMail: 1,
  isInternal: 1,
  subject: '',
  content: '',
  flag: -1,
  fileInfos: {},
  fileUploadConfig: {},
  sendFrom_internal: [],
  sendFrom_outer: [],
  sendTo_internal: [],
  sendTo_outer: [],
  op_isShowSendCc: 0,
  sendCc_internal: [],
  internaltonewIds: '',
  internalccnewIds: '',
  internalbccnewIds: '',
  sendCc_outer: [],
  op_isShowSendBcc: 0,
  sendBcc_internal: [],
  sendBcc_outer: [],
  op_showMoreOptions: 0,
  option_internal: [],
  option_outer: [],
  priority: 0,
  savesend: 1,
  // texttype: 0,
  texttype: 2,
  needReceipt: 0,
  timingdate: '',
  op_isTimingSend: 0,
  // upload
  upStatus: '',
  fileList: [],
  fileListB: [],
  upSetSub: false,
  // list
  signList: [],
  templateList: [],
  // response
  sendRes: {},
  // contacts
  focusTagGroup: '',
  searchValue: '',
  groupTree: [],
  contactsTreeLoading: false,
  contactsTreeListloading: false,
  contactsTreeListloadingId: '',
  // group
  hrmGroup: [],
  hasAll: 0,
  allInfo: {},
  mailid: '',
  oldmailid: '',
  // secrecy
  resourceClassification: {},
  classification: {},
  uploadTypeWhiteAuth: '0',
  // autoSaveDraft
  autofrequency: 1000 * 60,
  autoSave: 0,
  autoLoading: false,
  changeToNewPage: false,
};

export default class EmailNewStore {
  @observable loading = initState.loading;
  @observable sendingStatus = initState.sendingStatus;
  @observable editing = initState.editing;
  @observable initDatas = initState.initDatas;
  @observable hideRight = initState.hideRight;
  @observable mailAccountId = initState.mailAccountId;
  @observable hrmAccountid = initState.hrmAccountid;
  @observable isSendApart = initState.isSendApart;
  @observable op_showInnerAndOuter = initState.op_showInnerAndOuter;
  @observable isInternal = initState.isInternal;
  @observable subject = initState.subject;
  @observable content = initState.content;
  @observable flag = initState.flag;
  @observable fileInfos = initState.fileInfos;
  @observable fileUploadConfig = initState.fileUploadConfig;
  @observable sendFrom_internal = initState.sendFrom_internal;
  @observable sendFrom_outer = initState.sendFrom_outer;
  @observable sendTo_internal = initState.sendTo_internal;
  @observable sendTo_outer = initState.sendTo_outer;
  @observable op_isShowSendCc = initState.op_isShowSendCc;
  @observable sendCc_internal = initState.sendCc_internal;
  @observable internalccnewIds = initState.internalccnewIds;
  @observable internaltonewIds = initState.internaltonewIds;
  @observable internalbccnewIds = initState.internalbccnewIds;
  @observable sendCc_outer = initState.sendCc_outer;
  @observable op_isShowSendBcc = initState.op_isShowSendBcc;
  @observable sendBcc_internal = initState.sendBcc_internal;
  @observable sendBcc_outer = initState.sendBcc_outer;
  @observable op_showMoreOptions = initState.op_showMoreOptions;
  @observable option_internal = initState.option_internal;
  @observable option_outer = initState.option_outer;
  @observable priority = initState.priority;
  @observable savesend = initState.savesend;
  @observable texttype = initState.texttype;
  @observable needReceipt = initState.needReceipt;
  @observable timingdate = initState.timingdate;
  @observable op_isTimingSend = initState.op_isTimingSend;
  @observable upStatus = initState.upStatus;
  @observable fileList = initState.fileList;
  @observable fileListB = initState.fileListB;
  @observable upSetSub = initState.upSetSub;
  @observable signList = initState.signList;
  @observable templateList = initState.templateList;
  @observable sendRes = initState.sendRes;
  @observable focusTagGroup = initState.focusTagGroup;
  @observable searchValue = initState.searchValue;
  @observable groupTree = initState.groupTree;
  @observable contactsTreeLoading = initState.contactsTreeLoading;
  @observable contactsTreeListLoading = initState.contactsTreeListLoading;
  @observable contactsTreeListloadingId = initState.contactsTreeListloadingId;
  @observable hrmGroup = initState.hrmGroup;
  @observable hasAll = initState.hasAll;
  @observable allInfo = initState.allInfo;
  @observable texttypeClick = -1;
  @observable email_sendsessionUUid = '';
  @observable mailid = initState.mailid;
  @observable oldmailid = initState.oldmailid;
  @observable resourceClassification = initState.resourceClassification;
  @observable classification = initState.classification;
  @observable uploadTypeWhiteAuth = initState.uploadTypeWhiteAuth;
  @observable refreshTree = null; // internalTree
  @observable autofrequency = initState.autofrequency;
  @observable autoSave = initState.autoSave;
  @observable autoLoading = initState.autoLoading;
  @observable clearInstance = noop;
  @observable changeToNewPage = initState.changeToNewPage;

  @computed get selectedAllTo() {
    return isSelectedAll(toJS(this.sendTo_internal));
  }

  @computed get selectedAllCc() {
    return isSelectedAll(toJS(this.sendCc_internal));
  }

  @computed get selectedAllBcc() {
    return isSelectedAll(toJS(this.sendBcc_internal));
  }

  @computed get fileTotalSize() {
    let size = 0;
    this.fileList.forEach(({ filesizeByte }) => {
      size += filesizeByte || 0;
    });
    size /= 1024;
    return size > 1024
      ? `${(size / 1024).toFixed(2)} MB`
      : `${size.toFixed(2)} KB`;
  }

  @computed get fileTotalNumber() {
    return this.fileList.length;
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      const noSet =
        ((key === 'sendTo_internal' || key === 'internaltonewIds') &&
          this.selectedAllTo &&
          params[key].length !== 0) ||
        ((key === 'sendCc_internal' || key === 'internalccnewIds') &&
          this.selectedAllCc &&
          params[key].length !== 0) ||
        ((key === 'sendBcc_internal' || key === 'internalbccnewIds') &&
          this.selectedAllBcc &&
          params[key].length !== 0);
      !noSet && (this[key] = params[key]);
    });
    return this;
  };

  // 临时处理： 考虑到 content 每次都会由接口获取，这里不清空，防止接口新数据走在富文本异步 onchange 之前导致 clear 清空数据
  @action
  clear = () => {
    this.clearInstance();
    this.setState({
      ...initState,
      groupTree: this.groupTree,
      content: this.content,
    });
  };

  @action
  getInit = async (params, callback) => {
    this.editing = true;
    this.loading = true;
    // this.isInternal = Number(params.isInternal);
    const res = await Api.getInit(params);
    try {
      if (res.status === '1') {
        runInAction(() => {
          this.email_sendsessionUUid =
            res.email_sendsessionUUid && res.email_sendsessionUUid;
          const preReg = new RegExp(
            /^<div id=\"wea_rich_text_default_font\"[^>]+\>/,
          );
          let emailContent = Base64.decode(res.emailAddBean.content);
          emailContent = emailContent
            .replace(preReg, '')
            .replace(/<\/div>$/, '');
          const emailAddBean = { ...res.emailAddBean, content: emailContent };
          this.initDatas = emailAddBean;
          const {
            sendFrom_internal,
            sendFrom_outer,
            fileInfos: { fileList },
            mailId,
            flag,
            resourceClassification,
          } = res.emailAddBean;
          this.oldmailid = mailId;

          // 防止保存草稿重新保存，草稿箱进入的时候，默认带入mailid
          if (flag === 4) {
            this.setState({ mailid: mailId });
          }
          if (sendFrom_internal.length > 0) {
            const account = sendFrom_internal.filter(s => s.selected);
            this.hrmAccountid = (account.length === 1
              ? account[0]
              : sendFrom_internal[0]
            ).key;

            // 密级 key 值
            if (
              resourceClassification &&
              JSON.stringify(resourceClassification) !== '{}'
            ) {
              for (let item in resourceClassification) {
                if (!this.classification[item]) {
                  let selectedItem = resourceClassification[item].filter(
                    v => v.selected,
                  );
                  let selectedKey =
                    selectedItem.length > 0 ? selectedItem[0].key : '';
                  this.classification[item] = selectedKey;
                }
              }
            }
          }
          if (sendFrom_outer.length > 0) {
            const account = sendFrom_outer.filter(s => s.selected);
            this.mailAccountId = (account.length === 1
              ? account[0]
              : sendFrom_outer[0]
            ).key;
          }
          if (fileList) this.fileList = fileList;

          // 联系人点击写信带入默认数据（有待排查）
          let toarray = [];
          let idarray = params.to && params.to.split(',');
          let namearray = params.toname && params.toname.split(',');
          idarray &&
            idarray.forEach((v, k) => {
              let tobj = {};
              tobj.id = v;
              tobj.name = namearray ? namearray[k] : v;
              toarray.push(tobj);
            });

          // 此处无需二次组合，emailAddBean.sendTo_outer已有to传过来的参数，再次组合会重复数据
          //  toarray.push(...toJS(emailAddBean.sendTo_outer));
          //  emailAddBean.sendTo_outer = toarray;
          // ---------------end

          this.setState(emailAddBean);

          /* 自动保存草稿设置 */
          const { autoSave, saveInterval } = res.emailAddBean;
          this.autoSave = autoSave;
          this.autofrequency = saveInterval * 60 * 1000;

          if (callback) callback(res);
        });
      } else {
        message.error(res.msg);
      }
      runInAction(() => {
        this.loading = false;
      });
    } catch (e) {
      message.error(e);
      runInAction(() => {
        this.loading = false;
      });
    }
    runInAction(() => {
      this.loading = false;
    });
    return res;
  };

  @action('切换密级')
  changeSecrecy = (params) => {
    Api.filterSetecy(params).then((res) => {
      this.setState(res);
    });
  };

  @action
  changeAccount = (params) => {
    Api.getInit(params).then((res) => {
      this.sendFrom_outer = res.emailAddBean.sendFrom_outer;
      if (this.sendFrom_outer.length > 0) {
        const account = this.sendFrom_outer.filter(s => s.selected);
        this.mailAccountId = (account.length === 1
          ? account[0]
          : this.sendFrom_outer[0]
        ).key;
      }
    });
  };

  @action
  getSignList = async (params) => {
    this.loading = true;
    const res = await Api.getSignList(params);
    try {
      if (res.status === '1') {
        this.signList = res.signList;
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.loading = false;
    return res;
  };

  @action
  getTemplateList = async (params) => {
    this.loading = true;
    const res = await Api.getTemplateList(params);
    try {
      if (res.status === '1') {
        this.templateList = res.templateList;
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.loading = false;
    return res;
  };

  @action
  getContactsTree = async (params) => {
    this.contactsTreeLoading = true;
    this.contactsTreeListloadingId = '';
    const res = await Api.getContactsTree(params);
    try {
      if (res.status === '1') {
        this.groupTree = res.groupTree.map(t => ({
          ...t,
          current: 0,
          contactList: [],
          expandedKeys: [],
        }));
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.contactsTreeLoading = false;
    return res;
  };

  @action
  getContactsTreeList = async (params) => {
    this.contactsTreeListLoading = true;
    this.contactsTreeListloadingId = params.groupid;
    let addall = params.addall;
    let sendtype = params.sendtype;
    const res = await Api.getContactsTreeList(params);
    try {
      if (res.status === '1') {
        if (sendtype) {
          // 双击加载全部人员的时候无需再拼接
        } else {
          this.groupTree = toJS(this.groupTree).map((t) => {
            if (t.groupId === params.groupid) {
              return {
                ...t,
                contactList: t.contactList.concat(res.contactList),
                current: params.current,
              };
            }
            return t;
          });
        }
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.contactsTreeListLoading = false;

    if (addall) {
      let sets = [];
      if (sendtype == 'sendTo_outer') {
        if (this.sendTo_outer.length == 0) {
          this.sendTo_outer = this.sendTo_outer.concat(res.contactList);
          sets.push(...this.sendTo_outer);
        } else {
          let set1 = new Map();

          for (let i = 0; i < this.sendTo_outer.length; i++) {
            set1.set(this.sendTo_outer[i].id, toJS(this.sendTo_outer[i]));
          }

          for (let j = 0; j < res.contactList.length; j++) {
            set1.set(res.contactList[j].id, res.contactList[j]);
          }
          /* eslint-disable */
          for (let [key, value] of set1) {
            sets.push(value);
          }
          /* eslint-enable */
        }
        this.setState({
          [sendtype]: Array.from(toJS(sets)),
        });
      } else if (sendtype == 'sendCc_outer') {
        if (this.sendCc_outer.length == 0) {
          this.sendCc_outer = this.sendCc_outer.concat(res.contactList);
          sets.push(...this.sendCc_outer);
        } else {
          let set1 = new Map();

          for (let i = 0; i < this.sendCc_outer.length; i++) {
            set1.set(this.sendCc_outer[i].id, toJS(this.sendCc_outer[i]));
          }

          for (let j = 0; j < res.contactList.length; j++) {
            set1.set(res.contactList[j].id, res.contactList[j]);
          }
          /* eslint-disable */
          for (let [key, value] of set1) {
            sets.push(value);
          }
          /* eslint-enable */
        }
        this.setState({
          [sendtype]: Array.from(toJS(sets)),
        });
      } else if (sendtype == 'sendBcc_outer') {
        if (this.sendBcc_outer.length == 0) {
          this.sendBcc_outer = this.sendBcc_outer.concat(res.contactList);
          sets.push(...this.sendBcc_outer);
        } else {
          let set1 = new Map();

          for (let i = 0; i < this.sendBcc_outer.length; i++) {
            set1.set(this.sendBcc_outer[i].id, toJS(this.sendBcc_outer[i]));
          }

          for (let j = 0; j < res.contactList.length; j++) {
            set1.set(res.contactList[j].id, res.contactList[j]);
          }
          /* eslint-disable */
          for (let [key, value] of set1) {
            sets.push(value);
          }
          /* eslint-enable */
        }
        this.setState({
          [sendtype]: Array.from(toJS(sets)),
        });
      }
    }
    return res;
  };

  @action
  getHrmGroup = async (params = {}) => {
    const res = await Api.getHrmGroup(params);
    try {
      if (res.status === '1') {
        const { datas, hasAll, allInfo } = res;
        this.hasAll = hasAll;
        this.hrmGroup = datas;
        hasAll && (this.allInfo = allInfo);
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      message.error(e);
    }
    this.contactsTreeLoading = false;
    return res;
  };

  @action
  doSubmit = async (params) => {
    const isSave = params.savedraft;
    !this.autoSave && (this.loading = true);
    this.sendingStatus = isSave ? 'saving' : 'sending';
    if (this.autoSave) {
      this.autoLoading = true;
    }
    try {
      const res = await Api.sendEmail(params);
      this.sendRes = res;
      if (
        res.status === '1' &&
        (res.isSend === 'true' || res.isSend === 'draftSaved')
      ) {
        // 防止保存草稿重新保存，记录住保存后生成的mailid，再次保存带入
        if (res.isSend === 'draftSaved') {
          this.setState({ mailid: res.mailId });
          if (res.fileInfos) {
            this.fileList = res.fileInfos.fileList || [];
          }
        }
        this.sendingStatus = isSave ? 'saved' : 'success';
        if (!isSave && this.op_isTimingSend === 1) {
        } else {
          message.success(
            isSave
              ? getLabel(384403, '保存草稿成功')
              : getLabel(124904, '邮件发送成功'),
          );
        }
      } else {
        this.sendingStatus = 'error';
        message.error(
          `${getLabel(71, '邮件')}${
            isSave ? getLabel(30986, '保存') : getLabel(2083, '发送')
          }${getLabel(84566, '失败！')}`,
        );
      }
      this.editing = false;
      this.loading = false;
      this.autoLoading = false;
      return res;
    } catch (e) {
      this.sendingStatus = 'error';
      this.editing = false;
      this.loading = false;
      this.autoLoading = false;
      message.error(e);
    }
  };

  @action
  filterOutEmail = async (params) => {
    let res = await Api.filterOutEmail(params);
    return res;
  };
}
